using System;
using System.Net;
using System.Net.Sockets;

namespace Slobby.Server.Net {

    public delegate void ClientConnectedHandler (ClientConnection client);

    public class ClientListener {

        volatile bool running = false;

        TcpListener listener;
        IAsyncResult currentResult;

        public event ClientConnectedHandler ClientConnected;

        public ClientListener() {
            IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, 9001);
            listener = new TcpListener(endPoint);
        }

        public void BeginListen() {
            running = true;
            listener.Start();
            hookCallback();
        }

        public void EndListen() {
            running = false;
            listener.Stop();
        }

        private void hookCallback() {
            currentResult = listener.BeginAcceptTcpClient(callback, null);
        }

        private void callback(IAsyncResult result) {
            if (!result.IsCompleted) {
                return;
            }
            TcpClient newClient;
            try {
                newClient = listener.EndAcceptTcpClient(result);
            }
            catch (ObjectDisposedException) {
                return;
            }

            if (running) {
                hookCallback();
                if (ClientConnected != null)
                    ClientConnected(new ClientConnection (newClient));
            }
        }
    }
}
